/*NOTICE

This software was produced for the U. S. Government
under Contract No. FA8721-09-C-0002, and is
subject to the Rights in Noncommercial Computer Software
and Noncommercial Computer Software Documentation Clause
(DFARS) 252.227-7014 (JUN 1995)

(c) 2009 The MITRE Corporation. All Rights Reserved.
*/
package org.mitre.xmltransform.txt;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TxtOutputDocument {
	public TxtOutputDocument(File pOutputFile) {
		mOutputFile = pOutputFile;
		mItems = new ArrayList<String>();
	}
	
	public void finishDocument() {
	}
	
	public boolean writeOutput() {
		try {
			PrintWriter writer = new PrintWriter(mOutputFile);
			boolean newRecord = true;
			for (String item : mItems) {
				if (item == null) {
					writer.print(RECORD_SEPARATOR);
					newRecord = true;
				} else {
					if (!newRecord) {
						writer.print(ITEM_SEPARATOR);
					}
					writer.print(item);
					newRecord = false;
				}
			}
			
			writer.flush();
			writer.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public void addItem(String pItem) {
		mItems.add(pItem);
	}
	
	public void endRecord() {
		mItems.add(null);
	}

	public void addRecord(String[] pItems) {
		mItems.addAll(Arrays.asList(pItems));
		endRecord();
	}

	private static final String ITEM_SEPARATOR = "\t";
	private static final String RECORD_SEPARATOR = System.getProperty("line.separator"); 
	private List<String> mItems;
	private File mOutputFile;		
}
